package com.think.cloud.thinkshop.mall.service.email.impl;

import com.think.cloud.thinkshop.mall.service.email.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.template}")
    private String emailTemplate;
    @Value("${spring.mail.title}")
    private String emailTitle;

    @Override
    public String getDefaultTitle() {
        return emailTitle;
    }

    @Override
    public String getDefaultTemplate() {
        return emailTemplate;
    }

    @Override
    public void sendEmail(String email, String code) {
        String content = String.format(emailTemplate, code);
        this.sendTextEmail(email, emailTitle, content);
    }

    @Override
    public void sendTextEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(javaMailSender.getUsername());
        message.setTo(to);
        message.setSubject(emailTitle);
        message.setText(content);
        message.setSentDate(new Date());
        javaMailSender.send(message);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            // true 表示需要创建一一个 multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(javaMailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setSentDate(new Date());
            javaMailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生生异常!", e);
        }

    }
}
